package com.hunk.core.auth.controller;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hunk.core.auth.dto.RoleDTO;
import com.hunk.core.auth.entity.Role;
import com.hunk.core.auth.service.RoleService;
import com.hunk.core.json.base.JsonResponse;
import com.hunk.core.web.model.JpaOmGridPage;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageRequest;
import com.hunk.core.web.model.JpaOmGridPage.JpaPageResponse;
import com.hunk.utils.exception.CustomizeException;
import com.hunk.utils.io.Print;
@Controller
@RequestMapping("auth/role")
public class RoleController {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	RoleService roleService;
	
	@RequestMapping("/page")	
	public @ResponseBody JpaPageResponse<Role> getUserPage(HttpServletRequest request, 
			@RequestParam(required=false) Map<String, Object> params) {
		JpaOmGridPage.JpaPageRequest<Role> page = new JpaPageRequest<Role>(params);
		return roleService.findPageByParams(page);
	}
	
	@RequestMapping("/save")	
	public @ResponseBody JsonResponse<Role> save(
			@Valid @ModelAttribute() Role role, 
			BindingResult bindingResult) {
		Print.println(role);
		JsonResponse<Role> jr = new JsonResponse<Role>("操作失败");
		if (bindingResult.hasErrors()) {
			StringBuilder sb = new StringBuilder();
			for (FieldError fe : bindingResult.getFieldErrors()) {
				sb.append(fe.getDefaultMessage()).append("<br>");
			}
			jr.setError(sb.toString());
			return jr;
		}

		roleService.save(role);
		
		jr.setError("操作成功");
		jr.setResult(true);
		
		return jr;
	}
	
	@RequestMapping("/delete")	
	public @ResponseBody JsonResponse<Role> deleteUser(
			@ModelAttribute("role") Role role) {
		JsonResponse<Role> jr = new JsonResponse<Role>("操作失败");
		try {
			roleService.delete(role);
			jr.setError("操作成功");
			jr.setResult(true); 
		} catch (CustomizeException e) {
			logger.warn(e);
		}
		return jr;
	}
	@RequestMapping("/findAllAsTree")
	public @ResponseBody Set<RoleDTO> findAllAsTree() {
		return roleService.findAllAsTree();
	}
}
